

use bevy_ecs::{entity, prelude::Component, world::EntityMut};
use uuid::Uuid;

use super::{scene::Scene, components::IdComponent};

#[derive(Debug,Clone,PartialEq, Eq)]
pub struct Entity {
    pub             handle:     entity::Entity,
    pub(crate)      parent:     Option<entity::Entity>,
    pub(crate)      children:   Vec<entity::Entity>
}

impl Entity {
    pub fn new(handle:entity::Entity) -> Self {
        Self { handle, parent: None, children: Default::default() }
    }

    pub fn with_parent(handle:entity::Entity,parent:entity::Entity) -> Self {
        Self { handle, parent: Some(parent), children: Default::default() }
    }

    pub fn set_parent(&mut self , parent:entity::Entity) {
        self.parent = Some(parent);
    }

    pub fn add_child(&mut self,child:&mut Entity) {
        child.set_parent(self.handle);
        self.children.push(child.handle)
    }

    pub fn remove_child(&mut self , child:&entity::Entity) {
         if let Some((index,_)) = self.children.iter().enumerate().find(|(_,e)|{
            e.id() == child.id()
        }) {
            self.children.remove(index);
        }


    }

    pub fn add_component<T:Component>(&mut self , scene:&mut Scene ,component:T) {
     

        if let Some(mut entity_mut) = scene.world.get_entity_mut(self.handle) {

            // let id = std::any::TypeId::of::<T>();
            // match id {
            //     std::any::TypeId::of::<Rigidbody2DComponent>() => {
                    
            //     }
    
            //     _=>{}
            // }
            entity_mut.insert(component);
        }
    }


    pub fn get_component<'a,T:Component>(&self,scene:&'a Scene) -> Option<&'a T> {
        if let Some(entity_ref) = scene.world.get_entity(self.handle) {
            return entity_ref.get::<T>();
        }
        None
    }

    pub fn get_component_mut<'a>(&self,scene:&'a mut Scene) -> Option<EntityMut<'a>> {
        scene.world.get_entity_mut(self.handle)
    }

    pub fn has_component<T:Component>(&self,scene:&Scene) -> bool {
        if let Some(entity_ref) = scene.world.get_entity(self.handle) {
            return entity_ref.contains::<T>();
        }
        false
    }

    pub fn remove_component<T:Component>(&mut self,scene:&mut Scene) {
        if let Some(mut entity_mut) = scene.world.get_entity_mut(self.handle) {
            entity_mut.remove::<T>();
        }
    }

    pub fn is_some(&self,scene:&Scene) -> bool {
        scene.world.get_entity(self.handle).is_some()
    }

    pub fn get_entity(&self) -> bevy_ecs::entity::Entity {
        self.handle
    }

    pub fn get_uuid(&self,scene:&Scene) -> Uuid {
        self.get_component::<IdComponent>(scene).unwrap().id
    }

    pub fn get_child_nodes(&self) -> &Vec<entity::Entity> {
        &self.children
    }
}